import dayjs from 'dayjs'

const tel = (str = '') => {
  return str.replace(/(\d{3})\d*(\d{4})/, '$1****$2')
}
const parseTime = (str = '', format = 'YYYY-MM-DD') => {
  if (!str) {
    return ''
  }

  return dayjs(str).format(format)
}
const name = (name = '') => {
  let value = ''
  if (name.length === 2) {
    value = name.substr(0, 1) + '*'
  } else if (name.length > 2) {
    let char = ''
    for (let i = 0, len = name.length - 2; i < len; i++) {
      char += '*'
    }
    value = name.substr(0, 1) + char.slice(0, 2) + name.substr(-1, 1)
  } else {
    value = name
  }
  return value
}
const digitsRE = /(\d{3})(?=\d)/g
const currency = (value = '', currencyVal = '', decimals = 2) => {
  const numValue = parseFloat(value)

  if (numValue.toString() === 'NaN') {
    return value
  }

  const stringified = Math.abs(numValue).toFixed(decimals)
  const _int = decimals ? stringified.slice(0, -1 - decimals) : stringified
  const i = _int.length % 3
  const head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? ',' : '') : ''
  const _float = decimals ? stringified.slice(-1 - decimals) : ''
  const sign = numValue < 0 ? '-' : ''
  return sign + currencyVal + head + _int.slice(i).replace(digitsRE, '$1,') + _float
}
const star = (str = '') => {
  if (!str) {
    return
  }
  const date = dayjs(str)
  const month = date.month() + 1
  const day = date.date()
  const str2 = '魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯'
  const arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22]
  const rtv = str2.substr(month * 2 - (day < arr[month - 1] ? 2 : 0), 2)

  return rtv + '座'
}

const status = (str, map) => {
  const val = map[str]

  if (val != null) {
    return val
  }

  return ''
}

const sale = (str) => {
  if (str <= 100) {
    return str || '0'
  }

  if (str > 100 && str <= 1000) {
    return Math.floor(str / 100) + '*100'
  }

  if (str > 1000 && str <= 10000) {
    return Math.floor(str / 1000) + '*1000'
  }

  return Math.floor(str / 10000) + '万+'
}

const comment = (str) => {
  if (str == null || str <= 0) {
    return '暂无评论'
  }

  if (str <= 100) {
    return str
  }

  if (str <= 200) {
    return '100+评论'
  }

  if (str <= 500) {
    return '200+评论'
  }

  if (str <= 1000) {
    return '500+评论'
  }

  if (str <= 2000) {
    return '1000+评论'
  }

  if (str <= 5000) {
    return '2000+评论'
  }

  if (str <= 10000) {
    return '5000+评论'
  }

  return `${Math.floor(str / 10000)}万+评论`
}

const distance = (str, unit = 'm') => {
  const num = unit === 'km' ? str * 1000 : str * 1

  if (num < 1000) {
    return Math.floor(num) + 'm'
  }

  return (num / 1000).toFixed(1) + 'km'
}

const serviceTime = (str) => {
  return dayjs(str).format('YYYY年MM月DD日 A hh:mm').replace('AM', '上午').replace('PM', '下午')
}

const filters = {
  tel,
  parseTime,
  name,
  currency,
  star,
  status,
  sale,
  comment,
  distance,
  serviceTime,
}

export default filters
